#include <unistd.h>

#include "metrics/utility/Strings.hpp"
#include "metrics/utility/MemMetricsBuilder.hpp"

#define MEM_PERCENT_IDX 10
#define MEM_VSZ_IDX 11
#define MEM_RSS_IDX 13

namespace metrics
{
    MemMetricsBuilder::MemMetricsBuilder(const std::string &name, const std::string &help, const std::map<std::string, std::string> &labels)
        : GaugeMetricsBuilder(name, help, labels) {}

    MemMetricsBuilder::MemMetricsBuilder() : GaugeMetricsBuilder() {}

    MemMetricsBuilder::~MemMetricsBuilder() {}

    std::shared_ptr<Family<Gauge>> MemMetricsBuilder::metric_register(std::shared_ptr<MetricRegistry> registry)
    {
        //add cpu percent
        auto f = registry->add<Gauge>(_name, _help, _labels);
        auto percent = f->add({{"usage", "percent"}});
        auto vsz = f->add({{"usage", "vsz"}, {"unit", "kb"}});
        auto rss = f->add({{"usage", "rss"}, {"unit", "kb"}});
        auto pid = getpid();
        f->observe(
            [=]()
            {
                std::string cmd("ps -aux | grep ");
                cmd.append(std::to_string(pid));
                char buf[1024] = {0};
                FILE *fp = NULL;
                if ((fp = popen(cmd.c_str(), "r")) == NULL)
                {
                    printf("popen error!\n");
                    return;
                }
                fgets(buf, sizeof(buf), fp);
                auto strs = Strings::split(buf, " ");
                pclose(fp);
                percent->set(std::stod(strs[MEM_PERCENT_IDX]));
                vsz->set(std::stoi(strs[MEM_VSZ_IDX]));
                rss->set(std::stoi(strs[MEM_RSS_IDX]));
            });

        return f;
    }

    MemMetricsBuilder BuildMemMetrics()
    {
        return MemMetricsBuilder("memory", "", {});
    }

} // namespace metrics